<template>
  <view class="container">
    <!-- 标题栏 -->
    <uni-nav-bar
        title="公告详情"
        left-icon="left"
        @clickLeft="handleBack"
        background-color="#007aff"
        color="#ffffff">

      <template v-slot:right>
        <view class="nav-actions">
          <uni-icons
              type="edit"
              size="20"
              color="#ffffff"
              @click="handleEdit">
          </uni-icons>
        </view>
      </template>
    </uni-nav-bar>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <!-- 公告内容 -->
    <view v-else-if="notice" class="content-container">
      <!-- 公告头部信息 -->
      <view class="notice-header">
        <view class="header-title">
          <text class="title-text">{{ notice.noticeTitle }}</text>
        </view>

        <view class="header-meta">
          <view class="meta-row">
            <view class="meta-item">
              <uni-tag
                  :text="getNoticeTypeLabel(notice.noticeType)"
                  :type="notice.noticeType === '1' ? 'primary' : 'success'"
                  size="small">
              </uni-tag>
            </view>
            <view class="meta-item">
              <uni-tag
                  :text="notice.status === '0' ? '正常' : '关闭'"
                  :type="notice.status === '0' ? 'success' : 'error'"
                  size="small">
              </uni-tag>
            </view>
          </view>

          <view class="meta-row">
            <view class="meta-label">发布人：</view>
            <text class="meta-value">{{ notice.createBy || '-' }}</text>
          </view>

          <view class="meta-row">
            <view class="meta-label">发布时间：</view>
            <text class="meta-value">{{ parseTime(notice.createTime) }}</text>
          </view>

          <view class="meta-row" v-if="notice.updateTime && notice.updateTime !== notice.createTime">
            <view class="meta-label">更新时间：</view>
            <text class="meta-value">{{ parseTime(notice.updateTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 分隔线 -->
      <view class="divider"></view>

      <!-- 公告正文 -->
      <view class="notice-body">
        <view class="body-title">公告内容</view>

        <!-- 富文本内容显示 -->
        <view class="content-display">
          <!-- 支持富文本的平台 -->
          <!-- #ifndef MP-WEIXIN -->
          <rich-text
              :nodes="notice.noticeContent"
              class="rich-content">
          </rich-text>
          <!-- #endif -->

          <!-- 小程序降级显示 -->
          <!-- #ifdef MP-WEIXIN -->
          <view class="text-content">
            <text class="content-text">{{ getPlainText(notice.noticeContent) }}</text>
          </view>
          <!-- #endif -->
        </view>
      </view>

      <!-- 操作区域 -->
      <view class="action-section">
        <view class="action-title">相关操作</view>
        <view class="action-buttons">
          <button class="action-btn primary" @click="handleEdit">
            <uni-icons type="edit" size="16" color="#007aff"></uni-icons>
            <text>编辑公告</text>
          </button>
          <button class="action-btn" @click="handleShare">
            <uni-icons type="redo" size="16" color="#666"></uni-icons>
            <text>分享公告</text>
          </button>
          <button class="action-btn danger" @click="handleDelete">
            <uni-icons type="trash" size="16" color="#ff3b30"></uni-icons>
            <text>删除公告</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <uni-icons type="info" size="40" color="#ccc"></uni-icons>
      <text class="error-text">公告不存在或已被删除</text>
      <button class="retry-btn" @click="getNoticeDetail">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {delNotice, getNotice} from '@/api/system/notice'
import {parseTime} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 数据定义
const notice = ref(null)
const loading = ref(true)
const noticeId = ref('')

// 公告类型映射
const noticeTypeMap = {
  '1': '通知',
  '2': '公告'
}

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  if (options.noticeId) {
    noticeId.value = options.noticeId
    getNoticeDetail()
  } else {
    loading.value = false
    proxy.$modal.showToast('缺少公告ID参数')
  }
})

// 获取公告详情
async function getNoticeDetail() {
  loading.value = true

  try {
    const response = await getNotice(noticeId.value)
    if (response.code === 200) {
      notice.value = response.data
    } else {
      notice.value = null
      proxy.$modal.showToast(response.msg || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情失败:', error)
    notice.value = null
    proxy.$modal.showToast('获取公告详情失败')
  } finally {
    loading.value = false
  }
}

// 获取公告类型标签
function getNoticeTypeLabel(type) {
  return noticeTypeMap[type] || '未知'
}

// 获取纯文本内容（小程序使用）
function getPlainText(htmlContent) {
  if (!htmlContent) return ''
  // 移除HTML标签，获取纯文本
  return htmlContent.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim()
}

// 编辑公告
function handleEdit() {
  if (!notice.value) return

  uni.navigateTo({
    url: `/pages_system/notice/edit?mode=edit&noticeId=${notice.value.noticeId}`
  })
}

// 分享公告
function handleShare() {
  // #ifdef MP-WEIXIN
  uni.showShareMenu({
    withShareTicket: true,
    showShareItems: ['wechatFriends', 'wechatMoment']
  })
  // #endif

  // #ifndef MP-WEIXIN
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 0,
    href: '',
    title: notice.value?.noticeTitle || '公告分享',
    summary: getPlainText(notice.value?.noticeContent || ''),
    imageUrl: '',
    success: () => {
      proxy.$modal.showToast('分享成功')
    },
    fail: (err) => {
      console.log('分享失败:', err)
      proxy.$modal.showToast('分享失败')
    }
  })
  // #endif
}

// 删除公告
async function handleDelete() {
  if (!notice.value) return

  const result = await proxy.$modal.confirm(`是否确认删除公告"${notice.value.noticeTitle}"？`)
  if (result) {
    try {
      const response = await delNotice(notice.value.noticeId)
      if (response.code === 200) {
        proxy.$modal.showToast('删除成功')
        setTimeout(() => {
          handleBack()
        }, 1500)
      } else {
        proxy.$modal.showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      proxy.$modal.showToast('删除失败')
    }
  }
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-actions {
  padding-right: 15px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 50vh;
  padding: 20px;
}

.error-container {
  .error-text {
    margin: 15px 0;
    color: #999;
    font-size: 14px;
  }

  .retry-btn {
    background-color: #007aff;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
  }
}

.content-container {
  padding: 0 0 20px 0;
}

.notice-header {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 10px;

  .header-title {
    margin-bottom: 15px;

    .title-text {
      font-size: 20px;
      font-weight: bold;
      color: #333;
      line-height: 1.4;
    }
  }

  .header-meta {
    .meta-row {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .meta-item {
        margin-right: 8px;
      }

      .meta-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
        min-width: 80px;
      }

      .meta-value {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

.divider {
  height: 8px;
  background-color: #f5f5f5;
}

.notice-body {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 10px;

  .body-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }

  .content-display {
    .rich-content {
      line-height: 1.6;
      color: #555;

      // 富文本样式重置
      :global(p) {
        margin: 8px 0;
      }

      :global(img) {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
      }

      :global(ul), :global(ol) {
        padding-left: 20px;
        margin: 8px 0;
      }

      :global(li) {
        margin: 4px 0;
      }

      :global(blockquote) {
        border-left: 4px solid #ddd;
        padding-left: 16px;
        margin: 16px 0;
        color: #666;
      }
    }

    .text-content {
      .content-text {
        font-size: 15px;
        line-height: 1.6;
        color: #555;
        white-space: pre-wrap;
      }
    }
  }
}

.action-section {
  background-color: #fff;
  padding: 20px;

  .action-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }

  .action-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      height: 44px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: #fff;
      font-size: 15px;
      color: #666;

      &.primary {
        border-color: #007aff;
        color: #007aff;
      }

      &.danger {
        border-color: #ff3b30;
        color: #ff3b30;
      }

      &:active {
        background-color: #f8f9fa;
      }
    }
  }
}

/* 小程序适配 */
/* #ifdef MP-WEIXIN */
.rich-content {
  font-size: 14px;
}

/* #endif */

/* H5适配 */
/* #ifdef H5 */
.action-btn:hover {
  background-color: #f8f9fa;
}

/* #endif */
</style> 